<?php
/**
 * Created By Project
 * Author: 陈东
 * Copyright：陈东
 * Source Code：陈东
 * Explain：I shall not authorize for any other commercial purposes, law breakers must be prosecuted.
 */
namespace Admin\Controller;
use Think\Controller;

class UserController extends BaseController {
	/*
	 * 增加管理员显示
	 */
    public function useradd(){
    	$index=A("Index");
    	$index->gettypedata();
		$manages = A('Manages');
		$this->assign('manageslist',$manages->getallinfo());
		$this->assign('tpl', $this->tpl_select());
		$this->assign('account_type', $this->account_type());
		$this->display("Index/useradd");
    }
    /*
     * 显示用户管理列表
     */
    public function userlist(){
		$result = $this->userinfo();
		$this->assign('userlist',$result);
		$this->display("Index/userlist");
    }
	public function userinfo(){
		$user = D(C('TABLE_USER'));
		$result = $user->select();
		return $result;
	}
    /*
     * 显示用户管理编辑页
     */
    public function useredit($id=null){
    	$id = htmlspecialchars($id);
    	if(!empty($id)){
    		$index=A("Index");
    		$index->gettypedata();
    		$user = D(C('TABLE_USER'));
    		$result = $user->find($id);
    		$this->assign('result',$result);
			$manages = A('Manages');
			$this->assign('manageslist',$manages->getallinfo());
			$this->assign('tpl', $this->tpl_select());
			$this->assign('account_type', $this->account_type());
    		$this->display("Index/useredit");
    	}else{
    		$this->error('非法参数！','',2);
    	}
    }
	/**
	 * 账户类型
	 */
	private function account_type(){
		return array(
			array('account_name' => '企业', 'account_value' => 1),
			array('account_name' => '政府', 'account_value' => 2),
			array('account_name' => '国宣', 'account_value' => 3),
			array('account_name' => '娱乐', 'account_value' => 4)
		);
	}

    /**
     * 增加管理员
     */
    public function add(){
		$rbacstr 		= $this->pushma(I('post.ad_push_ma'));
		$account_type 	= $this->pushma(I('post.account_type'));
		$tplrbacstr 	= $this->pushma(I('post.select_tpl'));
    	$this->usermethodcontrol(null, 'add', '增加用户管理成功', '增加用户管理失败', null, $rbacstr, $tplrbacstr, $account_type);
    }
    /*
     * 编辑管理员
     */    
    public function edit($id=null){
		$rbacstr 		= $this->pushma(I('post.ad_push_ma'));
		$account_type 	= $this->pushma(I('post.account_type'));
		$tplrbacstr 	= $this->pushma(I('post.select_tpl'));
    	$id = htmlspecialchars($id);
    	if(!empty($id)){
    		$this->usermethodcontrol($id, 'save', '编辑用户成功', '编辑用户失败', U('userlist'), $rbacstr, $tplrbacstr, $account_type);
    	}else{
    		$this->error('非法参数！','',1);
    	}
    }
	protected function pushma($ad_push_ma = null){
		$rbacstr = null;
		if(!empty($ad_push_ma)){
			$str = null;
			if(is_array($ad_push_ma)){
				foreach($ad_push_ma as $v){
					$str .= $v.',';
				}
			}
			$rbacstr = rtrim($str,',');
		}
		return $rbacstr;
	}
    /*
     * 增加、编辑用户公用方法
     */
    protected function usermethodcontrol($id = null, $method, $success_message, $error_message, $bakurl, $rbacstr, $tplrbacstr, $account_type){
    	$rules = array(
    			array('username','require','用户名不能为空！'),
    			array('userpass1','userpass','两次输入密码不正确',0,'confirm'),
    			array('alias','require','用户别名不能为空！'),
    	);
    	if(empty($id)){
    		$rules = array(
    			array('username','','用户已经存在！',0,'unique',1),
    			array('userpass','require','密码不能为空！'),
    			array('userpass1','require','请再输一次密码！'),
    		);
    	}
    	$user = D(C('TABLE_USER'));
    	if(!$user->validate($rules)->create()){
    		$this->error($user->getError(),'',1);
    	}else{
    		$typeidarr = "";
    		foreach(I('post.typeid') as $v){
    			$typeidarr .= $v.",";
    		}
    		$typeid = rtrim($typeidarr,',');
    		//if(empty($typeid)) $this->error('请至少选择一个华人码','',2);
    		$user->typeid = $typeid;
    		if(empty($id)){
    			$user->userpass = md5(I('post.userpass'));
    		}else{
    			if(!empty(trim(I('post.userpass')))){
    				$user->userpass = md5(I('post.userpass'));
    			}else{
    				$user->userpass = $user->find($id)['userpass'];
    			}	
    		}
    		//die;
			$user->epname  = trim(I('post.epname'));
			$user->eplink  = trim(I('post.eplink'));
			$user->logoimg = trim(I('post.logoimg'));
			$user->codeimg = trim(I('post.codeimg'));

			$user->type 		= I('post.type');
			$user->state 		= I('post.state');
			$user->audit_ma 	= I('post.audit_ma');
			$user->audit_r 		= I('post.audit_r');
    		$user->crdate  		= date("Y-m-d H:i:s", time());
			$user->rbac    		= $rbacstr;
			$user->account_type = $account_type;
			$user->tplrbac 		= $tplrbacstr;
    		$where['id'] = !empty($id) ? $id : null;
    		$result = $user->where($where)->$method();
    		if($result !== false){
    			//A(C('TABLE_LOG'))->index(1,'增加用户管理成功');
    			$this->success($success_message,$bakurl);
    		}else{
    			//A(C('TABLE_LOG'))->index(0,'增加用户管理失败');
    			$this->error($error_message,'',2);
    		}
    	}
    }

	public function up(){
		$pra = "u".I('get.pra');
		$size = 31457280;
		$exts = array('pem');
		$rootpath = './assets/pem/';
		$upload = new \Think\Upload();			//实例化上传类
		$upload->maxSize   =     $size;			//设置附件上传大小30M
		$upload->exts      =     $exts;	//设置附件上传类型
		$upload->rootPath  =     $rootpath; 	//设置附件上传根目录
		// 上传单个文件
		$info   =   $_FILES[$pra];
		$info1   =   $upload->uploadOne($info);
		if(is_array($info1)){
			if($info1['size']>$size){
				echo 2;//超出限定范围30M
			}else if(empty($info1['name'])){
				echo 3;//没有上传文件
			}else{
				//echo C('WEBDOMAIN').'/'.$info['savepath'].$info['savename']; //返回路径
				echo ltrim($rootpath.$info1['savepath'].$info1['savename'],'.');
			}
		}else{
			echo 0;//上传失败
		}
	}

	/*
	 * 红包信息输出
	 */
	public function hb(){
		$userid = session('userinfo')['id'];
		$hbinfo = D(C('TABLE_HBINFO'));
		$res = $hbinfo->where(array('user_id'=>$userid))->find();
		if($res){
			$this->assign('hbinfo',$res);
		}
		$this->assign('typelist',$this->getmalist());
		$this->assign('md5confirm',md5('o4BL8s0_1cX8NaNq8JrR4E2KZAO4cf@huaren888'));
		$this->display();
	}

	public function activity(){
		$this->assign('typelist',$this->getmalist());
		$this->display();
	}
	protected function getmalist(){
		$type = D(C('TABLE_TYPE'));
		$usertype = session('userinfo')['type'];
		$userid = session('userinfo')['id'];
		$where['state'] = 1;
		if($usertype!=1){
			$where['userid'] = $userid;
		}
		$res = $type->where($where)->order('isvote desc,id desc')->select();
		return $res;
	}
	/*
	 * 保存红包接口
	 */
	public function hbinfoadd(){
//		$u_hbmin = I('post.u_hbmin');
//		$u_hbmax = I('post.u_hbmax');
//		if($u_hbmin<1){
//			$this->error('红包最小金额为1元','',1);hbinfoadd
//		}else if($u_hbmax>200){
//			$this->error('红包最大金额为200元','',1);
//		}
		$userid = session('userinfo')['id'];
		$hbinfo = D(C('TABLE_HBINFO'));
		$rules = array(
				array('u_appid','require','APPID不能为空！'),
				array('u_appsecret','require','appsecret不能为空！'),
				array('u_merchantid','require','商户ID不能为空！'),
				array('u_paykey','require','微信支付秘钥不能为空！'),
				array('u_cert','require','授权证书1不能为空！'),
				array('u_key','require','授权证书2不能为空！'),
		);
		if(!$hbinfo->validate($rules)->create()){
			$this->error($hbinfo->getError(),'',1);
		}else{
			if($this->issavehbinfo($userid)){
				//保存过，则更新
				$hbinfo->create();
				$hbinfo->date = date('Y-m-d H:i:s');
				$res = $hbinfo->where(array('user_id'=>$userid))->save();
			}else{
				//未保存，则添加
				$data['user_id'] = $userid;
				$data['u_appid'] = I('post.u_appid');
				$data['u_appsecret'] = I('post.u_appsecret');
				$data['u_merchantid'] = I('post.u_merchantid');
				$data['u_paykey'] = I('post.u_paykey');
				$data['u_cert'] = I('post.u_cert');
				$data['u_key'] = I('post.u_key');
				$data['status'] = I('post.status');
				$data['date'] = date('Y-m-d H:i:s');
				$res = $hbinfo->add($data);
			}
			if($res){
				header('Location:/Admin/User/hb');
			}else{
				$this->error('操作失败','',1);
			}
		}
	}
	//先判断是否保存过红包接口
    protected function issavehbinfo($userid){
		$hbinfo = D(C('TABLE_HBINFO'));
		$res = $hbinfo->where(array('user_id'=>$userid))->find();
		return $res;
	}

	public function center(){
		$userid = session('userinfo')['id'];
		$hbinfo = D(C('TABLE_USERINFO'));
		$res = $hbinfo->where(array('user_id'=>$userid))->find();
		if($res){
			$this->assign('info',$res);
		}
		$this->display();
	}
	/*
	 * 保存账号基本信息
	 */
	public function baseinfo(){
		$userid = session('userinfo')['id'];
		$hbinfo = D(C('TABLE_USERINFO'));
		$rules = array(
				array('p_name','require','企业名称不能为空！'),
				array('p_publicity','require','企业标语不能为空！'),
				array('p_web','require','企业网址不能为空！'),
				array('p_logo','require','需上传企业LOGO！'),
		);
		if(!$hbinfo->validate($rules)->create()){
			$this->error($hbinfo->getError(),'',1);
		}else{
			if($this->issavebaseinfo($userid)){
				//保存过，则更新
				$hbinfo->create();
				$res = $hbinfo->where(array('user_id'=>$userid))->save();
			}else{
				//未保存，则添加
				$data['user_id'] = $userid;
				$data['p_name'] = I('post.p_name');
				$data['p_publicity'] = I('post.p_publicity');
				$data['p_web'] = I('post.p_web');
				$data['p_logo'] = I('post.p_logo');
				$res = $hbinfo->add($data);
			}
			if($res){
				header('Location:/Admin/User/center');
			}else{
				$this->error('操作失败','',1);
			}
		}
	}
	//先判断是否保存过基本信息
	protected function issavebaseinfo($userid){
		$hbinfo = D(C('TABLE_USERINFO'));
		$res = $hbinfo->where(array('user_id'=>$userid))->find();
		return $res;
	}

	/*
	 * 指定一物一码的规则
	 */
	public function rule(){
		if($this->clearisvotev()){
			$ad_push_ma = I('post.ad_push_ma');
			$rule_id = 1;
			foreach ($ad_push_ma as $maid){
				$bresult = $this->bindadruletoma($rule_id,$maid);
				if($bresult==1){
					$this->error("ID:$maid 不具备一物一码的条件",'',3);
				}else if($bresult==0){
					$this->error("指定失败(".$maid.")",'',3);
				}
			}
			$this->success('指定成功');
		}else{
			$this->error("清理失败",'',1);
		}
	}
	protected function bindadruletoma($rule_id,$maid){
		$randnumber = D(C('TABLE_RANDNUMBER'));
		$res = $randnumber->where(array('ma_rootid'=>$maid))->count();
		if($res>0){
			$type = D(C('TABLE_TYPE'));
			$data['isvote'] = $rule_id;
			$res1 = $type->where(array('id'=>$maid))->save($data);
			if($res1){
				return 2;
			}else{
				return 0;
			}
		}else{
			return 1; //不具备一物一码的条件
		}

	}
	//先清理isvote的值
	protected function clearisvotev(){
		$type = D(C('TABLE_TYPE'));
		$data['isvote'] = null;
		$res = $type->where("isvote!=''")->save($data);
		if($res || $res==0){
			return true;
		}else{
			return false;
		}
	}


}